<template>
  <div class="space-y-6">
    <!-- 账号登录表单 -->
    <el-form
      ref="loginFormRef"
      :model="formData"
      :rules="formRules"
      class="mt-4"
      @submit.prevent="handleAccountLogin"
    >
      <!-- 用户名输入框 -->
      <el-form-item prop="username">
        <el-input
          v-model="formData.username"
          placeholder="请输入用户名/手机号"
          type="text"
          prefix-icon="User"
          autocomplete="username"
          class="w-full"
        />
      </el-form-item>

      <!-- 密码输入框 -->
      <el-form-item prop="password">
        <el-input
          v-model="formData.password"
          placeholder="请输入密码"
          type="password"
          prefix-icon="Lock"
          show-password
          autocomplete="current-password"
          class="w-full"
        />
      </el-form-item>

      <!-- 忘记密码链接 -->
      <div class="flex justify-end mb-2">
        <router-link
          to="/repass"
          class="text-sm text-primary hover:text-primary/80 transition-colors"
        >
          忘记密码？
        </router-link>
      </div>

      <!-- 登录按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          native-type="submit"
          class="w-full py-2 rounded-md transition-all"
          :loading="loginLoading"
        >
          账号登录
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 其他登录方式分割线 -->
    <div class="relative my-6">
      <div class="absolute inset-0 flex items-center">
        <div class="w-full border-t border-gray-200"></div>
      </div>
      <div class="relative flex justify-center">
        <span class="bg-white px-3 text-sm text-gray-500">其他登录方式</span>
      </div>
    </div>

    <!-- 扫码登录入口 -->
    <div class="flex justify-center">
      <el-button
        circle
        size="large"
        class="border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors"
        :loading="scanBtnLoading"
        @click="showScanModal = true"
        title="微信扫码登录"
      >
        <ChatDotRound class="w-6 h-6" />
      </el-button>
    </div>

    <!-- 注册/去首页链接 -->
    <div class="text-center mt-6 text-sm text-gray-600">
      暂不登录？
      <a
        href="/"
        class="text-primary hover:text-primary/80 transition-colors mr-2"
      >
        去首页
      </a>
      还没有账号？
      <router-link
        to="/reg"
        class="text-primary hover:text-primary/80 transition-colors"
      >
        立即注册
      </router-link>
    </div>

    <!-- 扫码登录弹窗 -->
    <el-dialog
      v-model="showScanModal"
      title="微信扫码登录"
      width="450px"
      :close-on-click-modal="false" 
      :destroy-on-close="true"
      @close="handleModalClose"
    >
      <WechatScanLogin
         @login-success="handleScanLoginSuccess"
      @close-modal="handleModalClose"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ChatDotRound } from "@element-plus/icons-vue";
import Cookies from "js-cookie";
import WechatScanLogin from "./WechatScanLogin.vue";
import { toLogin, getIp } from "../api/index.js"; // 仅保留原有接口
import { useRoute, useRouter } from "vue-router";
// 表单引用
const loginFormRef = ref(null);
// 表单数据（保持不变）
const formData = reactive({
  username: "",
  password: "",
});
// 表单验证规则（保持不变）
const formRules = reactive({
  username: [
    { required: true, message: "请输入用户名/手机号", trigger: "blur" },
    { min: 2, max: 20, message: "长度需在 2-20 个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" },
  ],
});

// 状态管理
const loginLoading = ref(false);
const scanBtnLoading = ref(false);
const showScanModal = ref(false);
const route = useRoute();
const router = useRouter();

// 打开扫码弹窗：直接设置为true，v-if会触发组件创建
const openScanModal = () => {
  showScanModal.value = true;
  console.log("[父组件] 扫码弹窗已打开，组件开始创建");
};

// 关闭扫码弹窗：设置为false，v-if会销毁组件
const handleModalClose = () => {
  showScanModal.value = false;
  console.log("[父组件] 扫码弹窗已关闭，组件已销毁");
};

// 扫码登录成功处理：通过emit让父组件统一处理
const handleScanLoginSuccess = (loginData) => {
  // 关闭扫码弹窗
  handleModalClose();
  // 通过emit让父组件统一处理登录成功逻辑
  emit("login-success", loginData);
};

// 对外暴露事件
const emit = defineEmits(["login-success"]);

// 组件加载时获取IP（保持不变）
onMounted(async () => {
  if (!Cookies.get("_i")) {
    try {
      const res = await getIp();
      if (res.code === 200 && res.data?.ip) {
        Cookies.set("_i", res.data.ip, { path: "/" });
      }
    } catch (e) {
      console.error("获取IP失败:", e);
    }
  }
});

/**
 * 账号密码登录（保持原有逻辑不变）
 */
async function handleAccountLogin() {
  try {
    await loginFormRef.value.validate();
    loginLoading.value = true;

    const params = {
      username: formData.username,
      password: formData.password,
      fp: Cookies.get("_f") || "",
      ip: Cookies.get("_i") || "",
    };

    const res = await toLogin(params);
    if (res.code === 200) {
      const { token, username, status } = res.data;
      if (status === "2") {
        ElMessage.warning("当前账号存在风险，请联系管理员审核");
        return;
      }
      // 正确触发登录成功事件，让父组件处理跳转
      emit("login-success", { token, username });
    } else {
      ElMessage.warning(res.msg || "登录失败，请检查账号密码");
    }
  } catch (error) {
    console.error("账号登录失败:", error);
    if (!(error instanceof Error && error.name === "ValidationError")) {
      ElMessage.error(error.message || "登录异常，请重试");
    }
  } finally {
    loginLoading.value = false;
  }
}

// 移除重复的函数定义
</script>